package org.xqp.org.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.xqp.basic.query.BaseQuery;
import org.xqp.basic.service.impl.BaseServiceImpl;

import org.xqp.basic.util.PageList;
import org.xqp.org.domain.Department;
import org.xqp.org.mapper.DepartmentMapper;
import org.xqp.org.query.DepartmentQuery;
import org.xqp.org.service.IDepartmentService;

import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void insert(Department department) {
        departmentMapper.add(department);
        /**
         * dirpath两种情况
         * 一：添加的是顶级部门  dirpath就是自己的id
         * 二：不是顶级部门dirthpath就是上上级部门的dirpath加上自己的id
         */
       /* if(department.getParent_id()==null){ // 如果是null就是顶级部门
            department.setDirPath("/"+department.getId());
        }else { // 如果不等于null就不是顶级部门
            Department patentDept = departmentMapper.loadByid(department.getParent().getId());
            String pdirPath = patentDept.getDirPath();
            department.setDirPath(pdirPath+"/"+department.getId());
        }*/

        //将数据更新到数据库
        update(department);

    }

    @Override
    @Transactional
    public void update(Department department) {
        /**
         * dirpath两种情况
         * 一：添加的是顶级部门  dirpath就是自己的id
         * 二：不是顶级部门dirthpath就是上上级部门的dirpath加上自己的id
         */
        if(department.getParent()==null || department.getParent().getId()==null){ // 如果是null就是顶级部门
            department.setDirPath("/"+department.getId());  //给department对象的DirPath属性赋值为/ 加上  department id
        }else { // 如果不等于null就不是顶级部门

            Long id = department.getParent().getId(); // 获取上级部门id
            Department patentDept = departmentMapper.loadByid(id);// 根据上级部门id获取上级部门对象

            String pdirPath = patentDept.getDirPath(); // 获取上级部门的DirPath
            department.setDirPath(pdirPath+"/"+department.getId()); // 给department的DirPath赋值
        }
        departmentMapper.update(department);
    }

    @Override
    public List<Department> queryTree() {
        return departmentMapper.loadTree();
    }
}
